#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import logging
import json
import aiohttp_jinja2
from io import BytesIO
from aiohttp import web

import db
import hlsutils
import proxyutils
import settings
from coreweb import query_string

routes = web.RouteTableDef()
module_name = 'hls'


def add_static():
    os.makedirs(settings.config['hls']['hls_last'], exist_ok=True)
    routes.static(
        '/hls_last/', path=settings.config['hls']['hls_last'], name='hls')
    os.makedirs(settings.config['hls']['poster'], exist_ok=True)
    routes.static(
        '/poster/', path=settings.config['hls']['poster'], name='poster')


add_static()


@routes.get('/root/load')
async def load_root(request):
    params = query_string(request)
    path = params.get('path', '/root')
    data = hlsutils.goto_dir(path)
    # session = db.create_session()
    # like_ = session.query(db.Fdfs).filter(db.Fdfs.path.like('/root%')).delete(synchronize_session=False)
    return {'code': 0, 'msg': data}


@routes.get('/%s/delete' % module_name)
async def delete(request):
    params = query_string(request)
    path = params.get('path', None)
    if path:
        parent, name = path.rsplit('/', 1)
        result = hlsutils.delete_by_path(parent, name)
        if result['status']:
            return {'code': 0, 'msg': parent}
    logging.error('failed to delete [%s]: %s' % (path, result['msg']))
    return {'code': -1, 'msg': 'failed to delete(%s): %s' % (path, result['msg'])}


@routes.post('/%s/import_data' % module_name)
async def import_data(request):
    params = await request.json()
    data = params['data']
    if len(data) <= 0:
        logging.error('failed to import data: %s' % (data))
        return {'code': -1, 'msg': 'failed to import data %s' % (data)}
    if '\'' in data:
        data = data.replace('\'', '\"').replace('None', 'null')
    result = hlsutils.import_data(json.loads(data, encoding='utf-8'))
    if result['status']:
        return {'code': 0, 'msg': '导入数据%s条' % result['msg']}
    logging.error('failed to import data %s: %s' % (data, result['msg']))
    return {'code': -1, 'msg': 'failed to import_data data %s: %s' % (data, result['msg'])}


@routes.get('/%s/export' % module_name)
async def export(request):
    params = query_string(request)
    fullpath = params['fullpath']
    parent, name = fullpath.rsplit('/', 1)
    if fullpath == '/root':
        parent, name = (None, fullpath)
    result = hlsutils.export(parent, name)
    if result['status']:
        return {'code': 0, 'msg': json.dumps(result['msg'], ensure_ascii=False)}
    logging.error('failed to export data[%s]: %s' % (fullpath, result['msg']))
    return {'code': -1, 'msg': 'failed to export data file(%s): %s' % (fullpath, result['msg'])}


@routes.get('/%s/rename' % module_name)
async def rename(request):
    params = query_string(request)
    fullpath = params['fullpath']
    newname = params['newname']
    result = hlsutils.rename(fullpath, newname)
    if result['status']:
        return {'code': 0, 'msg': fullpath.rsplit('/', 1)[0]}
    logging.error('failed to rename file[%s/%s]: %s' %
                  (fullpath, newname, result['msg']))
    return {'code': -1, 'msg': 'failed to rename file(%s, %s): %s' % (fullpath, newname, result['msg'])}


@routes.get('/%s/move' % module_name)
async def move(request):
    params = query_string(request)
    fullpath = params['fullpath']
    newpath = params['newpath']
    result = hlsutils.move(fullpath, newpath)
    if result['status']:
        return {'code': 0, 'msg': newpath}
    logging.error('failed to move file[%s/%s]: %s' %
                  (fullpath, newpath, result['msg']))
    return {'code': -1, 'msg': 'failed to move file(%s, %s): %s' % (fullpath, newpath, result['msg'])}


@routes.get('/%s/offline' % module_name)
async def offline(request):
    params = query_string(request)
    parent = params['parent']
    url = params['url']
    name = params['name']
    referer = params['referer']
    poster_referer = params['poster_referer']
    if len(url) <= 0:
        logging.error('offline url(%s) is None' % (url))
        return {'code': -1, 'msg': 'offline url(%s) is None' % (url)}
    result = hlsutils.offline(parent, url, name, referer, poster_referer)
    if result['status']:
        return {'code': 0, 'msg': parent}
    logging.error(
        'failed to offline(%s) download file[%s/%s]: %s' % (url, parent, name, result['msg']))
    return {'code': -1, 'msg': 'failed to offline(%s) download file[%s/%s]: %s' % (url, parent, name, result['msg'])}


@routes.get('/%s/newone' % module_name)
async def newone(request):
    params = query_string(request)
    parent = params['parent']
    url = params['url']
    name = params['name']
    referer = params['referer']
    poster_referer = params['poster_referer']
    if len(url) <= 0:
        logging.error('newone url(%s) is None' % (url))
        return web.json_response({'code': -1, 'msg': 'newone url(%s) is None' % (url)})
    data = [{'path': parent, 'name': name, 'content_type': '-', 'referer': url,
             'referer_referer': referer, 'poster_referer': poster_referer}]
    result = hlsutils.import_data(data)
    if result['status']:
        return web.json_response({'code': 0, 'msg': parent})
    logging.error('failed to newone(%s): %s' % (data, result['msg']))
    return web.json_response({'code': -1, 'msg': 'failed to newone(%s): %s' % (data, result['msg'])})


@routes.get('/%s/pause' % module_name)
async def pause(request):
    params = query_string(request)
    fullpath = params['fullpath']
    parent, name = fullpath.rsplit('/', 1)
    result = hlsutils.pause(parent, name)
    if result['status']:
        return {'code': 0, 'msg': parent}
    logging.error('failed to pause download file[%s]: %s' % (
        fullpath, result['msg']))
    return {'code': -1, 'msg': 'failed to pasue download file(%s): %s' % (fullpath, result['msg'])}


@routes.get('/%s/status' % module_name)
async def status(request):
    params = query_string(request)
    fullpath = params['fullpath']
    parent, name = fullpath.rsplit('/', 1)
    result = hlsutils.status(parent, name)
    if result['status']:
        return {'code': 0, 'msg': result['msg']}
    logging.error('failed to status download file[%s]: %s' % (
        fullpath, result['msg']))
    return {'code': -1, 'msg': 'failed to pasue download file(%s): %s' % (fullpath, result['msg'])}


@routes.get('/%s/restart' % module_name)
async def restart(request):
    params = query_string(request)
    fullpath = params['fullpath']
    parent, name = fullpath.rsplit('/', 1)
    result = hlsutils.restart(parent, name)
    if result['status']:
        return {'code': 0, 'msg': parent}
    logging.error('failed to offline download file[%s]: %s' % (
        fullpath, result['msg']))
    return {'code': -1, 'msg': 'failed to offline download file(%s): %s' % (fullpath, result['msg'])}


@routes.get('/%s/update' % module_name)
async def update(request):
    params = query_string(request)
    path = params['path']
    status = params['status']
    referer = params['referer']
    referer_referer = params['referer_referer']
    poster_referer = params['poster_referer']
    url = None if isinstance(
        params['url'], str) and 'None' == params['url'] else params['url']
    parent, name = path.rsplit('/', 1)
    result = hlsutils.update(parent, name, status,
                             referer, referer_referer, poster_referer, url)
    if result['status']:
        return {'code': 0, 'msg': parent}
    logging.error('failed to offline download file[%s]: %s' % (
        path, result['msg']))
    return {'code': -1, 'msg': 'failed to offline download file(%s): %s' % (path, result['msg'])}


@routes.get('/%s/load_src' % module_name)
async def update(request):
    params = query_string(request)
    url = params['url']
    dom_path = params['dom_path']
    get_res = params['get_res']
    mode = params['mode']
    if len(url) <= 0 or not url.startswith('http'):
        return {'code': -1, 'msg': 'failed to load_src url: %s' % (url)}
    if len(dom_path) <= 0:
        dom_path = '[]'
    if len(get_res) <= 0:
        get_res = '{}'
    if '\'' in dom_path:
        dom_path = dom_path.replace('\'', '\"').replace('None', 'null')
    if '\'' in get_res:
        get_res = get_res.replace('\'', '\"').replace('None', 'null')
    result = hlsutils.load_src(url, json.loads(
        dom_path), json.loads(get_res), mode=mode)
    if result['status']:
        return {'code': 0, 'msg': result['msg'] if isinstance(result['msg'], str) else json.dumps(result['msg'], ensure_ascii=False)}
    logging.error('failed to load_src[%s]: %s' % (url, result))
    return {'code': -1, 'msg': 'failed to load_src[%s]: %s' % (url, result['msg'])}


@routes.get('/%s/update_poster' % module_name)
async def update_poster(request):
    params = query_string(request)
    fullpath = params['fullpath']
    result = hlsutils.update_poster(fullpath)
    if result['status']:
        return {'code': 0, 'msg': result['msg']}
    logging.error('failed to update_poster[%s]: %s' % (fullpath, result))
    return {'code': -1, 'msg': 'failed to update_poster[%s]: %s' % (fullpath, result['msg'])}


@routes.get('/%s/mkdir/{name}' % module_name)
async def mkdir(request):
    name = request.match_info['name']
    params = query_string(request)
    parent = params['parent']
    result = hlsutils.makedir(parent, name)
    if result['status']:
        return {'code': 0, 'msg': parent}
    logging.error('failed to makedir(%s, %s): %s' %
                  (parent, name, result['msg']))
    return {'code': -1, 'msg': 'failed to makedir(%s, %s): %s' % (parent, name, result['msg'])}


@routes.get('/%s' % module_name)
async def root(request):
    params = query_string(request)
    path = params.get('path', '/root')
    mode = params.get('mode', 'true')
    data = hlsutils.goto_dir(path)
    # mode: true-列表, false-网格
    data['mode'] = True if mode == 'true' else False
    data = dict(data, **request.app['view_commons'])
    # print(data)
    return {'data': data, '__template__': 'hls.html'}
